﻿using System.Collections.Generic;
using System.Linq;
using Apps.Web.Core;
using Apps.Locale;
using System.Web.Mvc;
using Apps.Common;
using Apps.Models.PUB;
using Newtonsoft.Json;
using Apps.Models;
using Apps.BLL.HC;
using Apps.BLL.HuaChan;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Text.RegularExpressions;
using Apps.Models.HuaChan;

namespace Apps.Web.Areas.HuaChan.Controllers
{
    public class HuaChanProjectController : BaseController
    {
        HUACHAN_BLL huachanBll = new HUACHAN_BLL();
        ValidationErrors errors = new ValidationErrors();

        [SupportFilter]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        [SupportFilter(ActionName = "Index")]
        public JsonResult GetList()
        {
            int totalCount = 0;
            string queryStr = Utils.ObjectToStr(Request["queryStr"]);
            int pageSize = Utils.ObjToInt(Request["rows"], 15);
            int pageIndex = Utils.ObjToInt(Request["page"], 1);
            string sort = Utils.ObjectToStr(Request["sort"]);
            string order = Utils.ObjectToStr(Request["order"]);

            List<HUACHAN_PROJECT> list = huachanBll.ProjectList(pageIndex, pageSize, sort, order, ref totalCount, queryStr);
            return Json(new Pagination.PaginationResult<HUACHAN_PROJECT>(totalCount, list.ToList()));
        }

        [HttpPost]
        public JsonResult GetListDetail(string projectId)
        {
            List<HUACHAN_PROJECT_FIELDS> list = huachanBll.GetListDetail(projectId);
            return Json(list);
        }

        [HttpPost]
        public JsonResult GetFields(EasyUIDataGridPostModel model)
        {
            List<HUACHAN_PROJECT_FIELDS> fileds = huachanBll.GetListDetail(model.projectId);
            List<EasyUiDataGridColumnModel> colunms = new List<EasyUiDataGridColumnModel>();
            colunms.Add(new EasyUiDataGridColumnModel
            {
                align = "center",
                field = $"ID",
                width = 100,
                title = "编号",
                checkbox = true
            });
            fileds.ForEach(res =>
            {
                colunms.Add(new EasyUiDataGridColumnModel
                {
                    align = "center",
                    field = $"DATA{res.COLUMNIDX}",
                    width = 200,
                    title = res.FIELDNAME
                });
            });
            colunms.Add(new EasyUiDataGridColumnModel
            {
                align = "center",
                field = $"EXAMINE",
                width = 100,
                title = "审核状态"
            });
            colunms.Add(new EasyUiDataGridColumnModel
            {
                align = "center",
                field = $"EXMINETIME",
                width = 200,
                title = "审核时间"
            });
            colunms.Add(new EasyUiDataGridColumnModel
            {
                align = "center",
                field = $"ADDTIME",
                width = 200,
                title = "添加时间"
            });
            int totalCount = 0;
            var data = huachanBll.GetProjectData(model.pageIndex, model.pageSize, ref totalCount, "ADDTIME", "DESC", model.examine, model.projectId, model.beginTime, model.endTime);
            List<object> colObj = new List<object>();
            colObj.Add(colunms);
            return Json(new
            {
                columns = colObj,
                list = data,
                total = totalCount,
            }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult GetData(EasyUIDataGridPostModel model)
        {
            int totalCount = 0;
            model.pageIndex = model.pageIndex <= 0 ? 1 : model.pageIndex;
            model.pageSize = model.pageSize <= 0 ? 15 : model.pageSize;
            var data = huachanBll.GetProjectData(model.pageIndex, model.pageSize, ref totalCount, "ADDTIME", "DESC", model.examine, model.projectId, model.beginTime, model.endTime);
            List<object> colObj = new List<object>();
            return Json(new
            {
                //columns = colObj,
                list = data,
                total = totalCount,
            }, JsonRequestBehavior.AllowGet);
        }

        #region 创建
        [SupportFilter]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Create(HUACHAN_PROJECT model)
        {
            if (model != null)
            {
                if (string.IsNullOrEmpty(model.ID))
                {
                    return Json(JsonHandler.CreateMessage(0, "未指定编号!"));
                }
                if (string.IsNullOrEmpty(model.NAME))
                {
                    return Json(JsonHandler.CreateMessage(0, "请输入标题!"));
                }
                //bool isTeshu = Regex.Replace(model.NAME, "[\\u4e00-\\u9FA5A-Za-z0-9]", "", RegexOptions.IgnoreCase).Length > 0;
                //if (isTeshu)
                //{
                //    return Json(JsonHandler.CreateMessage(0, "标题不允许包含特殊字符!"));
                //}
                //if (!Regex.IsMatch(model.NAME, @"^[A-Za-z]+$"))
                //{
                //    return Json(JsonHandler.CreateMessage(0, "列名只能是英文字符，建议输入拼音!"));
                //}
                if (huachanBll.ProjectAny(model.NAME))
                {
                    return Json(JsonHandler.CreateMessage(0, "已存在相同名称的标题!"));
                }
                model.NAME = model.NAME.Trim();
                string jsonstr = JsonConvert.SerializeObject(model);
                model.ADDTIME = DateTime.Now;
                if (model.fields != null)
                    for (int i = 0; i < model.fields.Count; i++)
                    {
                        model.fields[i].ID = ResultHelper.NewId;
                        model.fields[i].COLUMNIDX = i + 1;
                        model.fields[i].PROJECTID = model.ID;
                        if (string.IsNullOrEmpty(model.fields[i].SORT))
                        {
                            model.fields[i].SORT = (i + 1).ToString();
                        }
                       
                        model.fields[i].FIELDNAME = model.fields[i].FIELDNAME.Trim();
                        model.fields[i].KEEPPOINT = ToInt(model.fields[i].KEEPPOINT).ToString();
                        model.fields[i].REQUIRED = model.fields[i].REQUIRED == "1" ? "是" : "否";
                    }
                var checkFileds = CheckFields(model.fields);
                if (!string.IsNullOrEmpty(checkFileds))
                {
                    return Json(JsonHandler.CreateMessage(0, checkFileds));
                }
                if (huachanBll.ProjecAdd(model))
                {
                    //LogHandler.WriteServiceLog(GetUserId(), jsonstr, "成功", "创建", "HUACHAN_PROJECT");
                    return Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    //LogHandler.WriteServiceLog(GetUserId(), jsonstr, "失败", "创建", "HUACHAN_PROJECT");
                    return Json(JsonHandler.CreateMessage(0, Resource.InsertFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail));
            }
        }

        #endregion

        public int ToInt(string val)
        {
            if (string.IsNullOrEmpty(val))
                return 0;
            int result = 0;
            int.TryParse(val, out result);
            return result;
        }

        #region 修改
        [SupportFilter]
        public ActionResult Edit(string id)
        {
            HUACHAN_PROJECT entity = huachanBll.ProjectInfo(id);
            ViewData.Model = entity;
            return View(entity);
        }

        public int GetIndex(List<int> indexCols)
        {
            //return indexCols.Max(m => m).ToString();
            for (int i = 1; i <= 50; i++)
            {
                if (!indexCols.Contains(i))
                    return i;
            }
            return 0;
        }

        /**
        *排序后，比较相邻的数据是否有重复的。
        */
        static bool IsSameWithSortAndCompare(int[] arr)
        {
            // 先排序
            Array.Sort(arr);

            //Console.WriteLine(string.Join(",", arr));

            // 对比相邻的数据是否相同
            for (var i = 0; i < arr.Length - 1; i++)
            {
                if (arr[i] == arr[i + 1])
                    return true;
            }
            return false;
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Edit(HUACHAN_PROJECT model)
        {
            if (model != null)
            {
                if (string.IsNullOrEmpty(model.NAME))
                {
                    return Json(JsonHandler.CreateMessage(0, "请输入标题!"));
                }
                //bool isTeshu = Regex.Replace(model.NAME, "[\\u4e00-\\u9FA5A-Za-z0-9]", "", RegexOptions.IgnoreCase).Length > 0;
                //if (isTeshu)
                //{
                //    return Json(JsonHandler.CreateMessage(0, "标题不允许包含特殊字符!"));
                //}
                //if (!Regex.IsMatch(model.NAME, @"^[A-Za-z]+$"))
                //{
                //    return Json(JsonHandler.CreateMessage(0, "列名只能是英文字符，建议输入拼音!"));
                //}
                if (huachanBll.ProjectAny(model.NAME, model.ID))
                {
                    return Json(JsonHandler.CreateMessage(0, "已存在相同名称的标题!"));
                }
                model.NAME = model.NAME.Trim();
                string jsonstr = JsonConvert.SerializeObject(model);
                List<int> indexCols = model.fields.Select(m => m.COLUMNIDX).ToList();
                if (model.fields != null)
                    for (int i = 0; i < model.fields.Count; i++)
                    {
                        indexCols = model.fields.Select(m => m.COLUMNIDX).ToList();
                        if (string.IsNullOrEmpty(model.fields[i].ID))
                        {
                            model.fields[i].ID = ResultHelper.NewId;
                        }
                        if (model.fields[i].COLUMNIDX <= 0)
                        {
                            var idx = GetIndex(indexCols);
                            model.fields[i].COLUMNIDX = idx == 0 ? (i + 1) : idx;
                        }
                        if (string.IsNullOrEmpty(model.fields[i].SORT))
                        {
                            model.fields[i].SORT = (i + 1).ToString();
                        }
                        model.fields[i].PROJECTID = model.ID;
                        model.fields[i].FIELDNAME = model.fields[i].FIELDNAME.Trim();
                        model.fields[i].KEEPPOINT = ToInt(model.fields[i].KEEPPOINT).ToString();
                        model.fields[i].REQUIRED = model.fields[i].REQUIRED == "1" ? "是" : "否";
                    }
                indexCols = model.fields.Select(m => m.COLUMNIDX).ToList();
                var checkFileds = CheckFields(model.fields);
                if (!string.IsNullOrEmpty(checkFileds))
                {
                    return Json(JsonHandler.CreateMessage(0, checkFileds));
                }
                if (IsSameWithSortAndCompare(indexCols.ToArray()))
                {
                    return Json(JsonHandler.CreateMessage(0, "索引存在重复!"));
                }
                if (huachanBll.ProjectEdit(model))
                {
                    //LogHandler.WriteServiceLog(GetUserId(), jsonstr, "成功", "修改", "HUACHAN_PROJECT");
                    return Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    //LogHandler.WriteServiceLog(GetUserId(), jsonstr, "失败", "修改", "HUACHAN_PROJECT");
                    return Json(JsonHandler.CreateMessage(0, Resource.InsertFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail));
            }
        }

        public string CheckFields(List<HUACHAN_PROJECT_FIELDS> fields)
        {
            if (fields == null)
                return "请至少配置一个填报列";
            if (fields.Count <= 0)
                return "请至少配置一个填报列";
            for (int i = 0; i < fields.Count; i++)
            {
                if (string.IsNullOrEmpty(fields[i].FIELDNAME))
                    return $"第{i + 1}列字段名称不能为空";
                if (string.IsNullOrEmpty(fields[i].FIELDTYPE))
                    return $"第{i + 1}列字段类型不能为空";
            }

            return "";

        }
        #endregion

        #region 删除
        [HttpPost]
        [SupportFilter]
        public ActionResult Delete(string id)
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                if (huachanBll.ThisProjectIsAnyData(id))
                {
                    return Json(JsonHandler.CreateMessage(0, "请先删除此化产表单中的所有数据!"));
                }
                if (huachanBll.ProjectDelete(id))
                {
                    LogHandler.WriteServiceLog(GetUserId(), "ID:" + id, "成功", "删除", "HUACHAN_PROJECT");
                    return Json(JsonHandler.CreateMessage(1, Resource.DeleteSucceed));
                }
                else
                {
                    string ErrorCol = "【删除失败】";
                    LogHandler.WriteServiceLog(GetUserId(), "ID" + id + "," + ErrorCol, "失败", "删除", "HUACHAN_PROJECT");
                    return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail));
            }
        }
        #endregion
    }
    public class EasyUIDataGridPostModel
    {
        public string projectId { get; set; }

        public int pageIndex { get; set; }
        public int pageSize { get; set; }
        public string examine { get; set; }

        public string beginTime { get; set; }

        public string endTime { get; set; }
    }
    public class EasyUiDataGridColumnModel
    {
        public string field { get; set; }

        public string title { get; set; }

        public int width { get; set; }

        public string align { get; set; }

        public bool hidden { get; set; }

        public bool checkbox { get; set; }
    }

}